<?php

namespace App\Lib\Uploads;


use App\Dengje\Utils\Settings;
use App\Models\WxAttachment;
use Qcloud\Cos\Client;

/**
 * 公共上传类
 * Class UploadHandler
 * @package App\Lib\Uploads
 */
class UploadHandler
{
    /**
     * 文件上传
     * @param $filePath
     * @return mixed
     */
//    public static function upload($filePath)
//    {
//        $storePath = date('Y/m/d', time());
//        $disk = config('admin.upload.disk');
//        $path = $filePath->store($storePath, $disk);
//        $domain = config('filesystems.disks.' . $disk . '.domains.https');
//        if (empty($model)) {
//            $model = new WxAttachment();
//            $model->path = $path;
//            $model->save();
//        }
//
//        return $domain . $path;
//    }

    /**
     * 统一文件上传方法
     * @param $filePath
     */
    public static function handle($file)
    {
        // 上传方式
        $ossType = Settings::get('ossType');
        // 路径
        $storePath = date('Y/m/d');
        // 文件名称
        $fileName = md5(uniqid()) . '.' . $file->extension();
        $key = $storePath . '/' . $fileName;
        // 本地上传
        if ($ossType == 'local') {
            $file->storeAs($storePath, $fileName);

            $key = 'storage/' .$key;
            $location = env('APP_URL').'/'. $key;
            $cosConfig['domain'] = env('APP_URL');
        }
        // 腾讯云cos
        if ($ossType == 'cosv5') {
            $cosConfig = json_decode(Settings::get('cosv5'),true);
            $cosClient = new Client(array(
                'region' => $cosConfig['region'],
                'credentials' => array(
                    'secretId' => $cosConfig['secretId'],
                    'secretKey' => $cosConfig['secretKey'],
                )
            ));
            ### 上传文件流
            try {
                $result = $cosClient->putObject(array(
                    'Bucket' => $cosConfig['bucket'] . '-' . $cosConfig['appId'],
                    'Key' => $key,
                    'Body' => fopen($file, 'rb')));
                $location = $cosConfig['domain'] . '/' . $key;
            } catch (\Exception $e) {
                echo "$e\n";
            }


        }


        // 保存到附件表
        $model = new WxAttachment();
        $model->path = $key;
        $model->domain = $cosConfig['domain'];
        $model->store_type = $ossType;
        $model->save();


        return [
            'key' => $key,
            'name' => $fileName,
            'path' => $storePath,
            'store_type' => $ossType,
            'url' => $location
        ];

    }
}
